﻿using EasyDDD.AdminModule.Application.CommandsSysAdminRole;
using EasyDDD.AdminModule.Domain.AggregateSysMenu;
using EasyDDD.AdminModule.Domain.DomainEventsSysAdminRoleMenu;

namespace EasyDDD.AdminModule.Application.DomainEventsHandler
{
    /// <summary>
    /// 管理员角色设置菜单列表领域事件处理
    /// </summary>
    /// <param name="mediator"></param>
    /// <param name="menuRepository"></param>
    /// <param name="logger"></param>
    internal class SysAdminRoleSetedMenuListDomainEventHandler(
        IMediator mediator,
        Repository.SysMenuRepository menuRepository,
        ILogger<SysAdminRoleSetedMenuListDomainEventHandler> logger)
        : IDomainEventHandler<SysAdminRoleSetMenuListDomainEvent>
    {
        public async Task Handle(SysAdminRoleSetMenuListDomainEvent @event, CancellationToken cancellationToken)
        {
            logger.LogInformation("领域事件 SysAdminRoleSetedMenuListDomainEventHandler {}", @event.SysAdminRole);

            var sysMenuIds = @event.SysAdminRole.SysAdminRoleMenuList.Select(f => new SysMenuId(f.SysMenuId)).ToArray();
            var menuList = await menuRepository.AsQueryable().Where(e => sysMenuIds.Contains(e.Id) && !string.IsNullOrEmpty(e.Permission)).ToListAsync();
            if (menuList == null || menuList.Count == 0)
            {
                return;
            }

            //设置角色权限
            var command = new SysAdminRoleSetRoleClaimCommand();
            command.Id = @event.SysAdminRole.Id;
            foreach (var menu in menuList)
            {
                command.RoleClaimList.Add(new SysAdminRoleSetRoleClaimCommandItem()
                {
                    ClaimType = ClaimTypes.MenuPermissions,
                    ClaimValue = menu.Permission,
                });
            }
            await mediator.Send(command, cancellationToken);
        }
    }
}
